package gat.common.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 你先别说话
 * @date 2025/3/13
 */
@Slf4j
public class TelegramBot {

    /**
     * 向群聊发送消息并艾特某人
     *
     * @param groupChatId 群聊的 chat_id
     * @param userId      用户的 user_id
     * @param username    用户的用户名
     * @param message     消息内容
     */
    public static void sendMessageToGroup(String token, long groupChatId, long userId, String username, String message) {
        try {
            // 构造请求URL
            String urlString = "https://api.telegram.org/bot" + token + "/sendMessage";
            URL url = new URL(urlString);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            JSONObject jsonBody = new JSONObject();
            jsonBody.put("chat_id", groupChatId);

            // 构造消息内容（使用 MarkdownV2 格式）
            String text = escapeMarkdownV2(message) + " [@" + escapeMarkdownV2(username) + "](tg://user?id=" + userId + ")";
            jsonBody.put("text", text);
            jsonBody.put("parse_mode", "MarkdownV2");

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.toString().getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                log.info("群聊消息发送成功！");
            } else {
                log.info("群聊消息发送失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向私聊发送消息
     *
     * @param privateChatId 私聊的 chat_id
     * @param message       消息内容
     */
    public static void sendMessageToPrivate(String token, long privateChatId, String message) {
        try {
            // 构造请求URL
            String urlString = "https://api.telegram.org/bot" + token + "/sendMessage";
            URL url = new URL(urlString);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 构造请求体
            String jsonInputString = "{\"chat_id\": \"" + privateChatId + "\", \"text\": \"" + message + "\"}";

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                log.info("私聊消息发送成功！");
            } else {
                log.error("私聊消息发送失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 转义 MarkdownV2 特殊字符
     */
    private static String escapeMarkdownV2(String text) {
        return text.replace("_", "\\_")
                .replace("*", "\\*")
                .replace("[", "\\[")
                .replace("]", "\\]")
                .replace("(", "\\(")
                .replace(")", "\\)")
                .replace("~", "\\~")
                .replace("`", "\\`")
                .replace(">", "\\>")
                .replace("#", "\\#")
                .replace("+", "\\+")
                .replace("-", "\\-")
                .replace("=", "\\=")
                .replace("|", "\\|")
                .replace("{", "\\{")
                .replace("}", "\\}")
                .replace(".", "\\.")
                .replace("!", "\\!");
    }

}
